﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Linq.Dynamic;
using SDT.Model;
using SDT.Lib.Common;
using SDT.Site.Properties;
using SDT.Site.Areas.User.ViewModels;
using SDT.Lib.Paging;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.Linq;
using SDT.Lib.Helpers;

namespace SDT.Site.Areas.User.Controllers
{
    public class ReadersController : Controller
    {

        /// <summary>
        /// Created by: Vietlv
        /// Created date: 15/09/2011
        /// Description: Manage Readers - Class Readers controler;
        /// </summary>

        SDTDataContext eDataContext = new SDTDataContext();

        #region GET: /Article/ Index(int? Page)
        public ActionResult Index(int? page)
        {
            try
            {
                if (page == null) page = 1;
                string order = UserState.getUserStateFromRequest("article.order", "order", "ID").ToString();
                string orderDir = UserState.getUserStateFromRequest("article.orderDir", "orderDir", "desc").ToString();
                int catID = ConfigManager.GetReaders();
                string keyword = UserState.getUserStateFromRequest("article.Keyword", "Keyword", "").ToString();
                keyword = keyword.Trim();
                int pageSize = int.Parse(UserState.getUserStateFromRequest("article.pageSize", "PageSize", 20).ToString());
                var pg = page.Value - 1;
                var articles = ArticleManager.GetArticles(catID, UserManager.GetUserId(),keyword, 0, 0, order, orderDir, pg, pageSize);
                ViewData["orderDir"] = orderDir;
                ViewData["order"] = order;

                return View(new ReadersIndexViewModel
                {
                    Articles = articles,
                    Keyword = keyword,
                    ImageRootUrl = Settings.Default.SiteRootUrl + Settings.Default.ArtileImagePreviewUrlPrefix
                });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region GET: /Article/Create  : Don't USE

        public ActionResult Create()
        {
            var company = eDataContext.Companies.ToList();
            var articleCategory = eDataContext.ArticleCategories
                                    .Where(e => e.ParentID == ConfigManager.GetReaders())
                                    .ToList();

            return View(new ReadersEditViewModel()
            {
                ArticleCategory = articleCategory
            });
        }
        #endregion

        #region POST: /Article/Create : Don't USE
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Create(CompanyEditViewModel cv)
        {
            try
            {
                // Modified by Vietlv (04/08/2011)
                if (eDataContext.Connection.State == System.Data.ConnectionState.Closed) eDataContext.Connection.Open(); //Vietlv
                eDataContext.Transaction = eDataContext.Connection.BeginTransaction();                                   //Vietlv               
                // TODO: Add insert logic here
                UpdateModel(cv);
                cv.Article.CatID = ConfigManager.GetTindoanhnghiep();
                cv.Article.AddDate = DateTime.Now;
                cv.Article.AddBy = UserManager.GetUserId();
                eDataContext.Articles.InsertOnSubmit(cv.Article);
                eDataContext.SubmitChanges();
                var companyid = Request["CompanyID"] != string.Empty ? Utils.ParseInt(Request["CompanyID"]) : 0;
                // Insert table ArticleCompanyMap
                if (companyid > 0)
                {
                    var articleCompanyMap = new ArticleCompanyMap();
                    articleCompanyMap.ArticleID = cv.Article.ID;
                    articleCompanyMap.CompanyID = companyid;
                    eDataContext.ArticleCompanyMaps.InsertOnSubmit(articleCompanyMap);
                }
                //Image upload
                HttpPostedFileBase fileImage = Request.Files["ArticleImage"];
                if (fileImage != null && fileImage.ContentLength > 0)
                {
                    cv.Article.ImagePath = Path.GetFileName(fileImage.FileName);
                    Uploads.UploadFile(fileImage, string.Format("{0}\\{1}", Settings.Default.SiteRootPath, Settings.Default.ArticleImageRootPath), "" + cv.Article.ID);
                }

                eDataContext.SubmitChanges();
                eDataContext.Transaction.Commit();
                return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                eDataContext.Transaction.Rollback();
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region GET: /Readers/Edit/5
        public ActionResult Edit(int id)
        {
            var article = eDataContext.Articles.Where(a => a.ID == id).SingleOrDefault();
            var listarticleCategories = eDataContext.ArticleCategories.Where(e => e.ParentID == ConfigManager.GetReaders()).ToList();

            var listCurrentTag = (from n in eDataContext.ArticleTagMaps where n.ArticleID == id select n.Tag.Keyword).ToList();
            var curentTag = "";
            foreach (var itemtag in listCurrentTag)
            {
                curentTag += itemtag.ToString() + ",";
            }
            return View(new ReadersEditViewModel
            {
                Article = article,
                ArticleCategory = listarticleCategories,
                ImageRootUrl = Settings.Default.SiteRootUrl + Settings.Default.ArtileImagePreviewUrlPrefix,
                CurrentListTag = curentTag,
                
                FileRootURL = Settings.Default.SiteRootUrl + Settings.Default.DocumentInArticlePreviewUrl

            });
        }
        #endregion
        #region POST: /Article/Edit/5
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Edit(int id, ReadersEditViewModel a)
        {
            try
            {
                if (eDataContext.Connection.State == System.Data.ConnectionState.Closed) eDataContext.Connection.Open();
                eDataContext.Transaction = eDataContext.Connection.BeginTransaction();
                // TODO: Add update logic here
                a.Article = eDataContext.Articles.Where(ar => ar.ID == id).SingleOrDefault();
                //a.Article.CatID = Request["CatID"] != string.Empty ? Utils.ParseInt(Request["CatID"]) : (int?)null;
                UpdateModel(a);

                //image upload
                HttpPostedFileBase fileImage = Request.Files["ArticleImage"];
                if (fileImage != null && fileImage.FileName.Length > 0)
                {
                    //Delete old image
                    if (!string.IsNullOrEmpty(a.Article.ImagePath) && System.IO.File.Exists(string.Format("{0}{1}\\{2}", Settings.Default.SiteRootPath, Settings.Default.ArticleImageRootPath, "" + a.Article.ID + "_" + a.Article.ImagePath)))
                        Uploads.DeleteFile(string.Format("{0}\\{1}\\{2}", Settings.Default.SiteRootPath, Settings.Default.ArticleImageRootPath, "" + a.Article.ID + "_" + a.Article.ImagePath));

                    //DO upload new image
                    a.Article.ImagePath = Path.GetFileName(fileImage.FileName);
                    Uploads.UploadFile(fileImage, string.Format("{0}{1}", Settings.Default.SiteRootPath, Settings.Default.ArticleImageRootPath), "" + a.Article.ID);

                }
                eDataContext.SubmitChanges();
                // Delete old ArticleTagMap
                var listArticleTagMap = eDataContext.ArticleTagMaps.Where(e => e.ArticleID == id).ToList();
                if (listArticleTagMap != null && listArticleTagMap.Count > 0) eDataContext.ArticleTagMaps.DeleteAllOnSubmit(listArticleTagMap);
                eDataContext.SubmitChanges();
                // insert ArticleTagMap
                var articleTageName = Request["TagName"] != null ? Request["TagName"].ToString() : string.Empty;
                if (articleTageName.Length > 0)
                {
                    var listTagName = articleTageName.Split(',');
                    if (listTagName.Length > 0)
                    {
                        for (int i = 0; i < listTagName.Length; i++)
                        {
                            var itemTagName = listTagName[i].ToString();
                            if (itemTagName.Length > 0)
                            {
                                var countTag = eDataContext.Tags
                                                .Where(e => e.Keyword.Trim().ToLower().Contains(itemTagName.Trim().ToLower())).FirstOrDefault();
                                // Case tag exist in database
                                if (countTag != null)
                                {
                                    ArticleTagMap articleTagMap = new ArticleTagMap();
                                    articleTagMap.ArticleID = a.Article.ID;
                                    articleTagMap.TagID = countTag.ID;
                                    eDataContext.ArticleTagMaps.InsertOnSubmit(articleTagMap);
                                    eDataContext.SubmitChanges();
                                }
                                else // Case tag don't exist
                                {
                                    // Create new Tags
                                    Tag newTag = new Tag();
                                    newTag.Keyword = itemTagName.Trim();
                                    newTag.AddBy = UserManager.GetUserId();
                                    newTag.AddDate = DateTime.Now;
                                    eDataContext.Tags.InsertOnSubmit(newTag);
                                    eDataContext.SubmitChanges();
                                    // Create new ArticleTagmap
                                    ArticleTagMap artTagMap = new ArticleTagMap();
                                    artTagMap.ArticleID = a.Article.ID;
                                    artTagMap.TagID = newTag.ID;
                                    eDataContext.ArticleTagMaps.InsertOnSubmit(artTagMap);
                                    eDataContext.SubmitChanges();
                                }
                            }
                        }
                    }
                }

                eDataContext.SubmitChanges();
                eDataContext.Transaction.Commit();
                return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                eDataContext.Transaction.Rollback();
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion       

        #region GET: /Article/Delete/5
        public ActionResult Delete(int id)
        {
            try
            {
                var item = eDataContext.Articles.Single(e => e.ID == id);
                return View(item);
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region POST: /Article/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {

                var item = eDataContext.Articles.Single(e => e.ID == id);
                if (item != null)
                {
                    Uploads.DeleteFile(string.Format("{0}{1}\\{2}", Settings.Default.SiteRootPath, Settings.Default.ArticleImageRootPath, item.ID + "_" + item.ImagePath));
                    // Delete articleCompanyMap
                    var artCompany = eDataContext.ArticleCompanyMaps.Where(e => e.ArticleID == id).ToList();
                    eDataContext.ArticleCompanyMaps.DeleteAllOnSubmit(artCompany);

                    // Delete artcleProjectMap
                    var artProject = eDataContext.ArticleProjectMaps.Where(e => e.ArticleID == id).ToList();
                    eDataContext.ArticleProjectMaps.DeleteAllOnSubmit(artProject);

                    // Delete articleEventMap
                    var artEvent = eDataContext.ArticleEventMaps.Where(e => e.ArticleID == id).ToList();
                    eDataContext.ArticleEventMaps.DeleteAllOnSubmit(artEvent);

                    // Delete articleTagMap
                    var artTag = eDataContext.ArticleTagMaps.Where(e => e.ArticleID == id).ToList();
                    eDataContext.ArticleTagMaps.DeleteAllOnSubmit(artTag);

                    // List Document
                    var listDocument = eDataContext.DocumentsInArticles.Where(e => e.ArticleID == id).Select(e => e.Document).ToList();
                    // Delete file in folder
                    foreach (var currentDocument in listDocument)
                    {
                        var filePath = Settings.Default.SiteRootPath + Settings.Default.DocumentInArticleRootPath + currentDocument.ID + "\\" + currentDocument.Path;
                        Uploads.DeleteFile(filePath);
                    }

                    // Delete Document in article 
                    var documentInArt = eDataContext.DocumentsInArticles.Where(e => e.ArticleID == id).ToList();
                    eDataContext.DocumentsInArticles.DeleteAllOnSubmit(documentInArt);
                    eDataContext.SubmitChanges();

                    // Delete list Document
                    eDataContext.Documents.DeleteAllOnSubmit(listDocument);
                    // Delete current article
                    eDataContext.Articles.DeleteOnSubmit(item);
                    eDataContext.SubmitChanges();
                }
                return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

    }
}
